import axios from 'axios'
import {Toast} from '../toast.js'
import {showLoading, hideLoading} from '../loading.js'
//扫一扫
function isJSON(str, pass_object) {
  if (pass_object && isObject(str)) return true;
  str = str.replace(/\s/g, '').replace(/\n|\r/, '');
  if (/^\{(.*?)\}$/.test(str)) return /"(.*?)":(.*?)/g.test(str);
  if (/^\[(.*?)\]$/.test(str)) {
    return str
      .replace(/^\[/, '')
      .replace(/\]$/, '')
      .replace(/},{/g, '}\n{')
      .split(/\n/)
      .map(function(s) {
        return isJSON(s);
      })
      .reduce(function(prev, curr) {
        return !!curr;
      });
  }
  return false;
}

export function QCodePlugin(that,types){
  let className = undefined;
  let url = undefined;
  let opts = undefined;
  cordova.exec(success, fail, "QCodePlugin", "start", [className || {}, url || {}, opts || {}]);
  let sessionId = localStorage.getItem('sessionId');
  function success(request) {
    console.log(request);
    console.log(request.length);
    if(request.length === 32){
        console.log(request);
        that.$router.push({path:'/main/traceSource', query:{traceSource:request}});
        return 
    } 
    let req = isJSON(request) ? JSON.parse(request) : request; 
    if(Object.prototype.toString.call(req) === "[object Object]"){
      //二维码
      if(req.modelCode){voucheridCode(req)};
      if(req.storeid){mendianCode(req)};
    } else if (Object.prototype.toString.call(req) === '[object Number]' || Object.prototype.toString.call(req) === '[object String]') {
             //条形码
             if (types == 2) {
               that.$router.push({ path: '/main/cartforoffline', query: { code: req } });
             } else {
               that.$router.push({ path: '/main/detail', query: { barcode: req } });
             }
           } else {
             Toast({
               message: '扫码失败！',
               iconClass: 'aui-iconfont aui-icon-close',
               duration: api.alertTime_2,
             });
           }
  };
//优惠券二维码
  function voucheridCode(req)  {
    showLoading();
  
    let config = {
      url: window.api.trade_host + "/marketCenter/receiveCouponCodesOffline/"+req.couponCode+"/"+req.storeCode,
      headers: {"sessionId": sessionId}
    }

    axios(config)
    .then(res => {
      if(res.status == 200){
        if (res.data.returnCode === 1) {
          hideLoading();
          Toast({
            message: res.data.msg || '领取成功!',
            type: "success",
            duration: api.alertTime_2
          });
          // that.$router.push('/main/myCoupons');
        }
        if (res.data.returnCode === 0) {
          hideLoading();
          Toast({
            message: res.data.msg || '领取失败!',
            type: "fail",
            duration: api.alertTime_2
          });
        }
      } else  {
        hideLoading();
        Toast({
          message: '网络错误!',
          type:'fail',
          duration: api.alertTime_2
        })
      }

    })
    .catch(error => {
      hideLoading();
      // alert(error);
    })
  };
//门店订单二维码
  function mendianCode(req) {
    showLoading();
    let val = req.storeCode ? req.storeCode : req.storeid;
    let a = {
      "storeOrderNo":req.posBillNo,
      "storeCode":val
    }
    let config = {
      method:'post',
      url: window.api.trade_host  + "/offLine/getCarInfo",
      headers: {'sessionId': sessionId,'Content-Type':'application/json'},
      data:JSON.stringify(a)
    }
    axios(config)
    .then(res => {
      if(res.status === 200){
        if(res.data.returnCode != 0){
          hideLoading();
          that.$router.push({path:'/main/confirmOrderOffline',query:{res:res}});
        } else {
          hideLoading();
          Toast({
            message: res.data.msg || '领取失败!',
            type: "fail",
            duration: api.alertTime_2
          });
        }
      } else  {
        hideLoading();
        Toast({
          message: '网络错误!',
          type: "fail",
          duration: api.alertTime_2
        });
      }
    })
    .catch(error => {
      hideLoading();
      // alert(error);
    })
  };
  //old
  //门店订单二维码
  // function mendianCode(req) {
  //   showLoading();
  //   let config = {
  //     url: window.api.trade_host  + "/orderOffline/getOrderGoodsInfo?storeOrderNo="  + req.posBillNo + "&shopId=" + req.storeid,
  //     headers: {"sessionId": sessionId}
  //   }
  //   axios(config)
  //   .then(res => {
  //     if(res.status === 200){
  //       if(res.data.returnCode != 0){
  //         hideLoading();
  //         that.$router.push({path:'/main/confirmOrderOffline',query:{res:res}});
  //       } else {
  //         hideLoading();
  //         Toast({
  //           message: res.data.msg || '领取失败!',
  //           type: "fail",
  //           duration: api.alertTime_2
  //         });
  //       }
  //     } else  {
  //       hideLoading();
  //       Toast({
  //         message: '网络错误!',
  //         type: "fail",
  //         duration: api.alertTime_2
  //       });
  //     }


  //   })
  //   .catch(error => {
  //     hideLoading();
  //     alert(error);
  //   })
  // };
  function fail(e) {
    console.log(e);
    hideLoading();
    // alert(e);
  };
//提示
  function tip(res) {
    if (res.returnCode === 1) {
      Toast({
        message: res.msg || '领取成功!',
        iconClass: "aui-iconfont aui-icon-correct",
        duration: window.api.alertTime
      });
    }
    if (res.returnCode === 0) {
       Toast({
         message: res.msg || '领取失败!',
         iconClass: "aui-iconfont aui-icon-close",
         duration: window.api.alertTime
       });
    }
  }
}


